//
//  MyOrderViewController.m
//  Free
//
//  Created by 张炜健 on 2018/5/16.
//  Copyright © 2018年 张炜健. All rights reserved.
//

#import "MyOrderViewController.h"
#import "OrderTableViewCell.h"
#import "MyOrderModel.h"
#import "PayPwdView.h"
#import "FilesHeader.h"
@interface MyOrderViewController ()<UITableViewDelegate,UITableViewDataSource,PayPwdViewDelegate>

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSArray *dataArr;

//底部弹出View
@property(nonatomic,strong)PayPwdView *aleartPasswordV;
@property(nonatomic,strong)NSString *postage;//运费
@property(nonatomic,strong)NSString *orderId;
@property(nonatomic,strong)NSString *orderType;
@property(nonatomic,assign)NSString *lijin;
@property(nonatomic,assign)NSString *price;
@property(nonatomic,assign)NSString *jianglijinprice;


@property(nonatomic,assign)int page;
@end

@implementation MyOrderViewController{
    UIImageView *errimg;
    int orderType_num;
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [self.tableView.mj_header beginRefreshing];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
}

- (void)setUI{
    self.view.backgroundColor = rgb(245, 245, 245);
}
- (void)request{
    _page = 10;
    [ZWJNetworkManager requestWithRequestData:@{@"pageNum":@"1",@"pageSize":@(_page),@"process":[NSString stringWithFormat:@"%li",(long)_process]} WithUrl:@"" WithWithCompletionBlockWithSuccess:^(NSDictionary *dic) {
        [self.tableView.mj_header endRefreshing];
        if ([dic[Code] intValue] == 200) {
            self->_dataArr = [MyOrderModel mj_objectArrayWithKeyValuesArray:dic[Response]];
            if (self->_dataArr.count > 0) {
                self->errimg.hidden = YES;
            }else{
                self->errimg.hidden = NO;
            }
            [self.tableView reloadData];
            
        }else{
            [self showWithTitle:dic[Response]];
        }
    } failure:^(id error) {
        [self.tableView.mj_header endRefreshing];
        if (@available(iOS 11.0,*)) {
            self->_tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }else{
            self.automaticallyAdjustsScrollViewInsets = false;
        }
    }];
    
}
- (void)moreRequest{
    _page = _page+10;
    [ZWJNetworkManager requestWithRequestData:@{@"pageNum":@"1",@"pageSize":@(_page),@"process":[NSString stringWithFormat:@"%li",(long)_process]} WithUrl:@"" WithWithCompletionBlockWithSuccess:^(NSDictionary *dic) {
        [self.tableView.mj_footer endRefreshing];
        if ([dic[Code] intValue] == 200) {
            self->_dataArr = [MyOrderModel mj_objectArrayWithKeyValuesArray:dic[Response]];
            [self.tableView reloadData];
            
        }else{
            [self showWithTitle:dic[Response]];
        }
    } failure:^(id error) {
        [self.tableView.mj_footer endRefreshing];
        
    }];
    
}
#pragma mark - lazy
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds  style:UITableViewStyleGrouped];
        //隐藏垂直滚动条
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
        _tableView.frame = CGRectMake(0, 0, KScreenWidth, KScreenHeight-Height_NavBar-44);
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(request)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(moreRequest)];
//        [_tableView.mj_header beginRefreshing];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        if (@available(iOS 11.0,*)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }else{
            self.automaticallyAdjustsScrollViewInsets = false;
        }
        errimg = [self addNoneGoodslist];
        errimg.top = 40;
        [_tableView addSubview:errimg];
        
    }
    return _tableView;
}

#pragma mark - DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    MyOrderModel *m = _dataArr[section];
    return m.shoppingOrderItemVoList.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
     MyOrderModel *m = _dataArr[indexPath.section];
    if (m.orderType == 6) {
        static NSString *ID = @"Cell";
        OrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"OrderTableViewCell" owner:self options:nil] objectAtIndex:3];
            
        }
//        cell.offlineTitleLabel.text =m.businessName;
//        [cell.businessImageV sd_setImageWithURL:[NSURL URLWithString:m.businessPic] placeholderImage:PlaceImage];
        
        return cell;
        
    }
    static NSString *ID = @"cell";
    OrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"OrderTableViewCell" owner:self options:nil] objectAtIndex:0];
        
    }
   
//    cell.model = m.shoppingOrderItemVoList[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
#pragma mark- tableViewCell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    MyOrderModel *m = _dataArr[indexPath.section];
    return 120;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 35;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = [UIColor whiteColor];
    UIView *topView = [[UIView alloc]init];
    topView.backgroundColor = rgb(245, 245, 245);
    [headerView addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(KScreenWidth));
        make.height.equalTo(@5);
        make.top.equalTo(headerView.mas_top);
    }];
    UIView *lineView = [[UIView alloc]init];
    lineView.backgroundColor = rgb(245, 245, 245);
    [headerView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(KScreenWidth));
        make.height.equalTo(@1);
        make.bottom.equalTo(headerView.mas_bottom);
    }];
    UILabel *statusStrLabel = [[UILabel alloc]init];
    MyOrderModel *m = _dataArr[section];
    if (m.process == 1) {
        statusStrLabel.text = @"待支付";
    }
    if (m.process == 2) {
        statusStrLabel.text = @"待发货";
    }
    if (m.process == 3) {
        statusStrLabel.text = @"待收货";
    }
    if (m.process == 4) {
        statusStrLabel.text = @"待评价";
    }
    if (m.process == 5) {
        statusStrLabel.text = @"已完成";
    }
    statusStrLabel.font = [UIFont boldSystemFontOfSize:12];
    statusStrLabel.textColor = rgb(255,110,2);
    [headerView addSubview:statusStrLabel];
    [statusStrLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(headerView.mas_right).offset(-20);
        make.centerY.equalTo(headerView.mas_centerY);
    }];
    UILabel *titleLabel = [[UILabel alloc]init];
    if (m.orderType == 1) {
        titleLabel.text = @"线上直营店（线上兑换）";
    }
    if (m.orderType == 2) {
        titleLabel.text = @"线上直营店（线上消费）";
    }
    if (m.orderType == 3) {
        titleLabel.text = @"线上直营店（线下消费）";
    }
    if (m.orderType == 4) {
        titleLabel.text = @"线上直营店（线下兑换）";
    }
    if (m.orderType == 5) {
        titleLabel.text = @"合作商家（线下消费）";
    }
    if (m.orderType == 6) {
        if (m.placeDistributorName) {
            titleLabel.text =  m.placeDistributorName;
        }else{
            titleLabel.text = m.businessName;;
        }
        
    }
    titleLabel.font = [UIFont systemFontOfSize:12];
    titleLabel.textColor = rgb(51,51,51);
    [headerView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headerView.mas_left).offset(20);
        make.centerY.equalTo(headerView.mas_centerY);
    }];
    return headerView;
}


//脚视图高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    MyOrderModel *m = _dataArr[section];
    if (m.process == 5 || m.process == 2) {
        //不显示按钮
        return 42;
    }else{
        return 80;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footerView = [[UIView alloc] init];
    footerView.backgroundColor = [UIColor whiteColor];
    UIView *topView = [[UIView alloc]init];
    topView.backgroundColor = rgb(245, 245, 245);
    [footerView addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(KScreenWidth));
        make.height.equalTo(@1);
        make.top.equalTo(footerView.mas_top);
    }];
    MyOrderModel *m = _dataArr[section];
    if (m.returnScore!=0) {
        NSString *str = [NSString stringWithFormat:@"预计返%@礼金",@(m.returnScore)];
        NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:str];
        text.yy_font = [UIFont systemFontOfSize:12];
        text.yy_color = [UIColor redColor];
        [text yy_setTextHighlightRange:NSMakeRange(3, str.length-3) color:rgb(255,110,2) backgroundColor:nil tapAction:nil];
        UILabel *returnLabel = [[UILabel alloc]init];
        
        if (m.process == 1 || m.process == 2 || m.process == 3 ) {
            returnLabel.attributedText = text;
        }else{
            returnLabel.text = @"";
        }
        [footerView addSubview:returnLabel];
        [returnLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(footerView.mas_top).offset(10);
            make.left.equalTo(footerView.mas_left).offset(20);
        }];
    }
    NSString *priceStr = @"";
    if (m.orderType == 2||m.orderType == 3||m.orderType == 6) {
        priceStr = [NSString stringWithFormat:@"￥%@",[@(m.totalFee) stringValue]];
    }
    if (m.orderType == 1) {//运费
        if (m.postage) {
            priceStr = [NSString stringWithFormat:@"%@礼金+运费￥%d",[@(m.realTotalFee) stringValue],m.postage];
        }else{
            priceStr = [NSString stringWithFormat:@"%@礼金",[@(m.realTotalFee) stringValue]];
        }
        
    }
    if (m.orderType == 4) {
        priceStr = [NSString stringWithFormat:@"%@礼金",[@(m.totalFee) stringValue]];
    }
    if (m.orderType == 5) {
        priceStr = [NSString stringWithFormat:@"%@推荐券",[@(m.totalFee) stringValue]];
    }
    NSString *str = @"";
    if (m.orderType == 6) {
        str = [NSString stringWithFormat:@"合计:%@",priceStr];
    }else{
        str = [NSString stringWithFormat:@"共%@件商品 合计:%@",@(m.goodsNum),priceStr];
    }
    
    NSRange range = [str rangeOfString:@":"];
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:str];
    text.yy_font = [UIFont systemFontOfSize:12];
    text.yy_color = rgb_51;
    [text yy_setFont:[UIFont boldSystemFontOfSize:12] range:NSMakeRange(range.location+1, str.length-range.location-1)];
    [text yy_setTextHighlightRange:NSMakeRange(range.location+1, str.length-range.location-1) color:rgb(255,110,2) backgroundColor:nil tapAction:nil];
    YYLabel *hejiLabel = [[YYLabel alloc]init];
    hejiLabel.attributedText = text;
    [footerView addSubview:hejiLabel];
    [hejiLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(footerView.mas_top).offset(15);
        make.right.equalTo(footerView.mas_right).offset(-20);
    }];
    //提示字
    UILabel *smallLabel = [[UILabel alloc]init];
    smallLabel.font = [UIFont systemFontOfSize:10];
    smallLabel.textColor = rgb(153, 153, 153);
    NSString *smallStr = @"";
    if (m.orderType == 2) {
        smallStr = [NSString stringWithFormat:@"(含运费￥%.2f)",m.postage/1.00];
    }
    if (m.orderType == 3 || m.orderType == 4 || m.orderType == 5) {
        smallStr = @"(线下自提)";
    }
    if (m.orderType == 1) {
        smallStr = @"不显示";
        smallLabel.textColor = [UIColor clearColor];
    }
    smallLabel.text = smallStr;
    [footerView addSubview:smallLabel];
    [smallLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(hejiLabel.mas_bottom).offset(0);
        make.right.equalTo(footerView.mas_right).offset(-20);
    }];
    //线
    UIView *lineView = [[UIView alloc]init];
    lineView.backgroundColor = rgb(245, 245, 245);
    [footerView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(KScreenWidth));
        make.height.equalTo(@1);
        make.top.equalTo(smallLabel.mas_bottom).offset(5);
    }];
    //按钮
    NSString *LeftBtnName = @"";
    NSString *RightBtnName = @"";
    if (m.process == 1) {
        LeftBtnName = @"取消订单";
        RightBtnName = @"去支付";
    }
    if (m.process == 2) {
        //不显示
    }
    if (m.process == 3) {
        LeftBtnName = @"查看物流";
        RightBtnName = @"确认收货";
    }
    if (m.process == 4) {
        RightBtnName = @"评价";
    }
    if (m.process == 5) {
        //不显示按钮
    }
   
    UIButton *rightBtn = [[UIButton alloc]init];
    rightBtn.tag = m.process;
    [rightBtn setTitle:RightBtnName forState:UIControlStateNormal];
    [rightBtn clipUIView:5];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [rightBtn setBackgroundColor:rgb(255,186,20)];
    [rightBtn setTitleColor:rgb(51, 51, 51) forState:UIControlStateNormal];
    [footerView addSubview:rightBtn];
    [rightBtn addTarget:self action:@selector(rightActionTap:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@75);
        make.height.equalTo(@25);
        make.right.equalTo(footerView.mas_right).offset(-20);
        make.top.equalTo(lineView.mas_bottom).offset(5);
    }];
    UIButton *leftBtn = [[UIButton alloc]init];
    leftBtn.tag = m.process;
    [leftBtn setTitle:LeftBtnName forState:UIControlStateNormal];
    [leftBtn clipUIView:5];
    leftBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [leftBtn setBorder:rgb(153, 153, 153) With:1];
    [leftBtn setTitleColor:rgb(51, 51, 51) forState:UIControlStateNormal];
    [footerView addSubview:leftBtn];
    [leftBtn addTarget:self action:@selector(leftActionTap:) forControlEvents:UIControlEventTouchUpInside];
    [leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@75);
        make.height.equalTo(@25);
        make.right.equalTo(rightBtn.mas_left).offset(-10);
        make.top.equalTo(lineView.mas_bottom).offset(5);
    }];
    if ([LeftBtnName isEqualToString:@""]) {
        [leftBtn setHidden:YES];
    }
    if ([RightBtnName isEqualToString:@""]) {
        [rightBtn setHidden:YES];
    }

    //runtime传值
    objc_setAssociatedObject(leftBtn, "object", m, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(rightBtn, "object", m, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    return footerView;
}

-(void)leftActionTap:(UIButton *)sender{
    MyOrderModel *m = objc_getAssociatedObject(sender, "object");
    NSLog(@"%@",@(m.ID));
    if (sender.tag == 1) {
        NSLog(@"取消订单");
        [self cancelOrder:[@(m.ID) stringValue]];

    }

    if (sender.tag == 3) {
        NSLog(@"查看物流");
//        CheckLogisticsViewController *vc = [[CheckLogisticsViewController alloc]init];
//        vc.orderId = [@(m.ID) stringValue];
//        [self.navigationController pushViewController:vc animated:YES];

    }
}

-(void)rightActionTap:(UIButton *)sender{
    MyOrderModel *m = objc_getAssociatedObject(sender, "object");
    NSLog(@"%@",@(m.ID));
    if (sender.tag == 1) {
        NSLog(@"去支付");
        
        _postage = [@(m.postage) stringValue];
        _orderId = [@(m.ID) stringValue];
        _orderType = [@(m.orderType) stringValue];
        //1线上兑换 2线上消费 3 线下消费 4线下兑换 5 商家兑换 6合作商家
        if (m.orderType == 2||m.orderType == 3) {//￥

        }
        if (m.orderType == 1||m.orderType == 4) {//礼金
          
        }
        if (m.orderType == 5) {//推荐券
            //弹出选择支付方式
            orderType_num = m.orderType;
         
        }
        if (m.orderType == 6) {
            //弹出选择支付方式
  
        }
        
    }
    if (sender.tag == 3) {
        NSLog(@"确认收货");
        [self querenshouhuoWithID:[@(m.ID) stringValue] andModel:m];
    }
    if (sender.tag == 4) {
        NSLog(@"评价");
      
    }
}
-(void)cancelOrder:(NSString *)orderId{
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"取消订单" message:@"是否确定取消订单?" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *tureAction=[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //取消订单
        [ZWJNetworkManager requestWithRequestData:@{@"orderId":orderId} WithUrl:@"" WithWithCompletionBlockWithSuccess:^(NSDictionary *dic) {
            if ([dic[Code] intValue] == 200) {
                NSLog(@"取消订单成功");
                [self request];
            }else{
                [self showWithTitle:dic[Response]];
            }
        } failure:^(id error) {
        }];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:tureAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma 查询钱包
-(void)requsetMoney{
    [ZWJNetworkManager requestWithRequestData:nil WithUrl:@"" WithWithCompletionBlockWithSuccess:^(NSDictionary *dic) {
        if ([dic[Code] intValue] == 200) {
            
           
            
        }
    } failure:^(id error) {
    }];
}
//确认收货
-(void)querenshouhuoWithID:(NSString *)orderId andModel:(MyOrderModel*)m{
    NSString *aleatStr = nil;
    if (m.returnScore >0.00 && m.orderType == 2) {
        aleatStr = @"确认收货后,对应礼金将自动打入至您的账户,且不能发起售后";
    }else{
        aleatStr = @"";
    }
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"确认收货" message:aleatStr preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *tureAction=[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //确认收货
        [ZWJNetworkManager requestWithRequestData:@{@"orderId":orderId} WithUrl:@"" WithWithCompletionBlockWithSuccess:^(NSDictionary *dic) {
            if ([dic[Code] intValue] == 200) {
                NSLog(@"收货成功");
                [self request];
            }else{
                [self showWithTitle:dic[Response]];
            }
        } failure:^(id error) {
        }];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
//    [tureAction setValue:[UIColor blackColor] forKey:@"_titleTextColor"];
//    [cancelAction setValue:[UIColor blackColor] forKey:@"_titleTextColor"];
    [alert addAction:tureAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}


#pragma mark- cell 代理协议方法的实现
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MyOrderModel * m = _dataArr[indexPath.section];
    NSLog(@"订单id = %@",[@(m.ID) stringValue]);
    if (m.orderType == 1 || m.orderType == 2) {
//        OrderDetailsViewController *controller = [[OrderDetailsViewController alloc]init];
//        controller.orderID = [@(m.ID) stringValue];
//        [self.navigationController pushViewController:controller animated:YES];
    }else{
//        OfflineDetailsViewController *controller = [[OfflineDetailsViewController alloc]init];
//        controller.orderID = [@(m.ID) stringValue];
//        [self.navigationController pushViewController:controller animated:YES];
    }
}

@end
